
//使用开放API获取音源的纯前端音乐播放器

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Harmony Player</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #2a4d69);
            color: #fff;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            display: flex;
            background: rgba(25, 20, 40, 0.85);
            border-radius: 20px;
            overflow: hidden;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
            height: 90vh;
        }
        
        .sidebar {
            width: 280px;
            background: rgba(15, 10, 30, 0.9);
            padding: 25px 15px;
            display: flex;
            flex-direction: column;
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            overflow-y: auto;
        }
        
        .logo {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            color: #9b5de5;
        }
        
        .logo i {
            margin-right: 10px;
            font-size: 28px;
        }
        
        .nav-section {
            margin-bottom: 30px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #7f8c8d;
            margin-bottom: 15px;
            padding-left: 10px;
        }
        
        .nav-item {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .nav-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .nav-item.active {
            background: rgba(155, 93, 229, 0.4);
        }
        
        .nav-item i {
            margin-right: 12px;
            font-size: 18px;
            width: 24px;
            text-align: center;
        }
        
        .playlist-section {
            flex-grow: 1;
            overflow-y: auto;
        }
        
        .playlist-item {
            padding: 10px 15px;
            border-radius: 8px;
            display: flex;
            justify-content: space-between;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .playlist-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .playlist-name {
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 160px;
        }
        
        .song-count {
            color: #7f8c8d;
            font-size: 13px;
        }
        
        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 30px;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            gap: 15px;
        }
        
        .search-box {
            display: flex;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 30px;
            padding: 8px 15px;
            flex: 1;
            max-width: 500px;
        }
        
        .search-box input {
            background: transparent;
            border: none;
            color: white;
            outline: none;
            flex: 1;
            padding: 5px 10px;
        }
        
        .search-box button {
            background: transparent;
            border: none;
            color: #9b5de5;
            cursor: pointer;
        }
        
        .import-btn {
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            border: none;
            border-radius: 30px;
            color: white;
            padding: 12px 25px;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
            white-space: nowrap;
        }
        
        .import-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(155, 93, 229, 0.4);
        }
        
        .import-btn i {
            margin-right: 8px;
        }
        
        /* 播放器样式 */
        .player-container {
            background: rgba(30, 25, 50, 0.7);
            border-radius: 20px;
            padding: 30px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        
        .now-playing {
            display: flex;
            margin-bottom: 40px;
            gap: 30px;
        }
        
        .album-art {
            width: 220px;
            height: 220px;
            border-radius: 15px;
            background: linear-gradient(45deg, #9b5de5, #00bbf9);
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            flex-shrink: 0;
        }
        
        .album-art img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .album-art i {
            font-size: 80px;
            color: rgba(255, 255, 255, 0.7);
        }
        
        .song-info {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            min-width: 0;
        }
        
        .song-title {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-artist {
            font-size: 20px;
            color: #9b5de5;
            margin-bottom: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-album {
            font-size: 16px;
            color: #7f8c8d;
            margin-bottom: 30px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .controls {
            display: flex;
            align-items: center;
        }
        
        .control-btn {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            border: none;
            color: white;
            font-size: 18px;
            margin: 0 10px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .control-btn:hover {
            background: rgba(155, 93, 229, 0.5);
            transform: scale(1.1);
        }
        
        .play-btn {
            width: 70px;
            height: 70px;
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            font-size: 24px;
        }
        
        /* 进度条 */
        .progress-container {
            margin: 30px 0;
        }
        
        .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 14px;
            color: #bdc3c7;
        }
        
        .progress-bar {
            height: 6px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 3px;
            overflow: hidden;
            cursor: pointer;
        }
        
        .progress {
            height: 100%;
            background: linear-gradient(90deg, #9b5de5, #f15bb5);
            width: 30%;
            border-radius: 3px;
            position: relative;
        }
        
        .progress::after {
            content: '';
            position: absolute;
            right: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            background: white;
            border-radius: 50%;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .progress-bar:hover .progress::after {
            opacity: 1;
        }
        
        /* 播放列表 */
        .playlist-title {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
        }
        
        .playlist-title i {
            margin-right: 10px;
            color: #9b5de5;
        }
        
        .song-list {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .song-item {
            display: flex;
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .song-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .song-item.playing {
            background: rgba(155, 93, 229, 0.3);
        }
        
        .song-number {
            width: 30px;
            color: #7f8c8d;
            display: flex;
            align-items: center;
        }
        
        .song-details {
            flex: 1;
            min-width: 0;
        }
        
        .song-item-title {
            font-weight: 500;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-item-artist {
            font-size: 13px;
            color: #7f8c8d;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .song-duration {
            color: #7f8c8d;
            display: flex;
            align-items: center;
            padding-left: 10px;
        }
        
        /* 搜索区域 */
        .search-results {
            margin-top: 20px;
            background: rgba(30, 25, 50, 0.7);
            border-radius: 15px;
            padding: 20px;
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .results-title {
            font-size: 18px;
            font-weight: 600;
        }
        
        .result-item {
            display: flex;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .result-item:hover {
            background: rgba(155, 93, 229, 0.2);
        }
        
        .result-art {
            width: 50px;
            height: 50px;
            border-radius: 8px;
            background: linear-gradient(45deg, #9b5de5, #00bbf9);
            margin-right: 15px;
            flex-shrink: 0;
            overflow: hidden;
        }
        
        .result-art img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        .result-details {
            flex: 1;
            min-width: 0;
        }
        
        .result-title {
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .result-artist {
            font-size: 13px;
            color: #7f8c8d;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* 响应式设计 */
        @media (max-width: 900px) {
            .container {
                flex-direction: column;
                height: auto;
            }
            
            .sidebar {
                width: 100%;
                border-right: none;
                border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            }
            
            .now-playing {
                flex-direction: column;
                align-items: center;
                text-align: center;
            }
            
            .album-art {
                margin-bottom: 25px;
            }
            
            .controls {
                justify-content: center;
            }
        }
        
        @media (max-width: 600px) {
            .header {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-box, .import-btn {
                width: 100%;
                max-width: none;
            }
            
            .player-container {
                padding: 20px;
            }
            
            .now-playing {
                gap: 20px;
            }
            
            .album-art {
                width: 180px;
                height: 180px;
            }
            
            .song-title {
                font-size: 26px;
            }
            
            .song-artist {
                font-size: 18px;
            }
        }
        
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: rgba(155, 93, 229, 0.5);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: rgba(155, 93, 229, 0.8);
        }
        
        .loader {
            text-align: center;
            padding: 20px;
            color: #9b5de5;
        }
        
        .loader i {
            font-size: 24px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 30px;
            color: #7f8c8d;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #9b5de5;
        }
        
        /* 错误提示 */
        .error-message {
            color: #ff6b6b;
            padding: 10px;
            text-align: center;
            font-size: 14px;
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <div class="logo">
                <i class="fas fa-music"></i>
                <span>Harmony Player</span>
            </div>
            
            <div class="nav-section">
                <div class="section-title">发现音乐</div>
                <div class="nav-item active" data-section="search">
                    <i class="fas fa-search"></i>
                    <span>搜索</span>
                </div>
                <div class="nav-item" data-section="recommend">
                    <i class="fas fa-fire"></i>
                    <span>推荐歌单</span>
                </div>
                <div class="nav-item" data-section="charts">
                    <i class="fas fa-chart-line"></i>
                    <span>排行榜</span>
                </div>
            </div>
            
            <div class="nav-section">
                <div class="section-title">我的音乐</div>
                <div class="nav-item" data-section="history">
                    <i class="fas fa-history"></i>
                    <span>播放历史</span>
                </div>
                <div class="nav-item" data-section="local">
                    <i class="fas fa-folder"></i>
                    <span>本地音乐</span>
                </div>
                <div class="nav-item" data-section="favorites">
                    <i class="fas fa-heart"></i>
                    <span>我的收藏</span>
                </div>
            </div>
            
            <div class="playlist-section">
                <div class="section-title">我的歌单</div>
                <div class="playlist-item" data-playlist="default">
                    <span class="playlist-name">默认歌单</span>
                    <span class="song-count">0首</span>
                </div>
                <div class="playlist-item" data-playlist="favorites">
                    <span class="playlist-name">收藏夹</span>
                    <span class="song-count">0首</span>
                </div>
                <div class="playlist-item" data-playlist="recent">
                    <span class="playlist-name">最近播放</span>
                    <span class="song-count">0首</span>
                </div>
            </div>
        </div>
        
        <!-- 主内容区 -->
        <div class="main-content">
            <div class="header">
                <div class="search-box">
                    <input type="text" id="searchInput" placeholder="搜索音乐、歌单、歌手...">
                    <button id="searchBtn"><i class="fas fa-search"></i></button>
                </div>
                <button class="import-btn" id="importBtn">
                    <i class="fas fa-plus"></i>
                    导入本地音乐
                </button>
            </div>
            
            <div class="player-container">
                <div id="errorMessage" class="error-message"></div>
                
                <div class="now-playing">
                    <div class="album-art">
                        <i class="fas fa-music" id="defaultArtIcon"></i>
                        <img id="albumArt" src="" alt="Album Art" style="display: none;">
                    </div>
                    <div class="song-info">
                        <h1 class="song-title" id="songTitle">Harmony Player</h1>
                        <div class="song-artist" id="songArtist">准备好享受音乐</div>
                        <div class="song-album" id="songAlbum">选择歌曲开始播放</div>
                        
                        <div class="controls">
                            <button class="control-btn" id="prevBtn">
                                <i class="fas fa-step-backward"></i>
                            </button>
                            <button class="control-btn play-btn" id="playBtn">
                                <i class="fas fa-play"></i>
                            </button>
                            <button class="control-btn" id="nextBtn">
                                <i class="fas fa-step-forward"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <div class="progress-container">
                    <div class="progress-info">
                        <span id="currentTime">0:00</span>
                        <span id="totalTime">0:00</span>
                    </div>
                    <div class="progress-bar" id="progressBarContainer">
                        <div class="progress" id="progressBar"></div>
                    </div>
                </div>
                
                <div class="volume-container">
                    <div class="progress-info">
                        <span>音量</span>
                        <span id="volumePercent">70%</span>
                    </div>
                    <div class="progress-bar" id="volumeBarContainer">
                        <div class="progress" id="volumeBar" style="width: 70%;"></div>
                    </div>
                </div>
                
                <h2 class="playlist-title">
                    <i class="fas fa-list"></i>
                    当前播放列表
                </h2>
                
                <div class="song-list" id="playlist">
                    <div class="empty-state" id="emptyPlaylist">
                        <i class="fas fa-music"></i>
                        <p>播放列表为空</p>
                        <p>请导入本地音乐或搜索添加歌曲</p>
                    </div>
                </div>
                
                <div class="search-results" id="searchResults" style="display: none;">
                    <div class="results-header">
                        <div class="results-title">搜索结果</div>
                        <div id="resultsCount">0 首歌曲</div>
                    </div>
                    <div class="results-container" id="resultsContainer">
                        <div class="empty-state" id="emptyResults">
                            <i class="fas fa-search"></i>
                            <p>输入关键词搜索音乐</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <input type="file" id="fileInput" accept="audio/*" multiple style="display: none;">
    
    <script>
        const audioPlayer = new Audio();
        let currentPlaylist = [];
        let currentSongIndex = -1;
        let isPlaying = false;
        let searchResultsData = [];
        
        // DOM元素
        const playBtn = document.getElementById('playBtn');
        const prevBtn = document.getElementById('prevBtn');
        const nextBtn = document.getElementById('nextBtn');
        const importBtn = document.getElementById('importBtn');
        const fileInput = document.getElementById('fileInput');
        const searchInput = document.getElementById('searchInput');
        const searchBtn = document.getElementById('searchBtn');
        const playlist = document.getElementById('playlist');
        const searchResults = document.getElementById('searchResults');
        const resultsContainer = document.getElementById('resultsContainer');
        const emptyPlaylist = document.getElementById('emptyPlaylist');
        const errorMessage = document.getElementById('errorMessage');
        
        function initPlayer() {
            loadLocalMusic();
            
            playBtn.addEventListener('click', togglePlay);
            prevBtn.addEventListener('click', playPrev);
            nextBtn.addEventListener('click', playNext);
            
            importBtn.addEventListener('click', () => fileInput.click());
            fileInput.addEventListener('change', handleFileSelect);
            
            searchInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') searchMusic();
            });
            searchBtn.addEventListener('click', searchMusic);
            
            document.getElementById('progressBarContainer').addEventListener('click', seekAudio);
            document.getElementById('volumeBarContainer').addEventListener('click', adjustVolume);
            
            audioPlayer.addEventListener('timeupdate', updateProgress);
            audioPlayer.addEventListener('ended', playNext);
            audioPlayer.addEventListener('loadedmetadata', () => {
                document.getElementById('totalTime').textContent = formatTime(audioPlayer.duration);
            });
            
            audioPlayer.addEventListener('error', () => {
                showError('音频加载失败，请尝试其他歌曲');
            });
            
            audioPlayer.volume = 0.7;
        }
        
        function loadLocalMusic() {
            if (typeof wusiStorage !== 'undefined') {
                const savedMusic = wusiStorage.getItem('localMusic');
                if (savedMusic && savedMusic.length > 0) {
                    currentPlaylist = savedMusic;
                    renderPlaylist();
                    updatePlaylistCount();
                }
            }
        }
        
        function saveLocalMusic() {
            if (typeof wusiStorage !== 'undefined') {
                wusiStorage.setItem('localMusic', currentPlaylist);
            }
        }
        
        function showError(message) {
            errorMessage.textContent = message;
            errorMessage.style.display = 'block';
            
            setTimeout(() => {
                errorMessage.style.display = 'none';
            }, 3000);
        }
        
        function togglePlay() {
            if (currentPlaylist.length === 0) {
                showError('播放列表为空，请先添加歌曲');
                return;
            }
            
            if (isPlaying) {
                audioPlayer.pause();
                playBtn.querySelector('i').className = 'fas fa-play';
                isPlaying = false;
            } else {
                if (currentSongIndex === -1) {
                    currentSongIndex = 0;
                    loadSong(currentSongIndex);
                }
                
                if (!audioPlayer.src) {
                    loadSong(currentSongIndex);
                }
                
                audioPlayer.play().then(() => {
                    playBtn.querySelector('i').className = 'fas fa-pause';
                    isPlaying = true;
                }).catch(err => {
                    showError('播放失败: ' + (err.message || '未知错误'));
                    console.error('播放错误:', err);
                });
            }
        }
        
        function playPrev() {
            if (currentPlaylist.length === 0) return;
            
            currentSongIndex--;
            if (currentSongIndex < 0) {
                currentSongIndex = currentPlaylist.length - 1;
            }
            loadSong(currentSongIndex);
            if (isPlaying) {
                audioPlayer.play().catch(err => {
                    showError('播放失败: ' + (err.message || '未知错误'));
                });
            }
        }
        
        function playNext() {
            if (currentPlaylist.length === 0) return;
            
            currentSongIndex++;
            if (currentSongIndex >= currentPlaylist.length) {
                currentSongIndex = 0;
            }
            loadSong(currentSongIndex);
            if (isPlaying) {
                audioPlayer.play().catch(err => {
                    showError('播放失败: ' + (err.message || '未知错误'));
                });
            }
        }
        
        function loadSong(index) {
            if (index < 0 || index >= currentPlaylist.length) return;
            
            const song = currentPlaylist[index];
            
            document.getElementById('songTitle').textContent = song.title;
            document.getElementById('songArtist').textContent = song.artist || '未知艺术家';
            document.getElementById('songAlbum').textContent = song.album || '未知专辑';
            
            document.querySelectorAll('.song-item').forEach(item => {
                item.classList.remove('playing');
            });
            document.querySelectorAll('.song-item')[index].classList.add('playing');
            
            const albumArt = document.getElementById('albumArt');
            const defaultIcon = document.getElementById('defaultArtIcon');
            if (song.cover) {
                albumArt.src = song.cover;
                albumArt.style.display = 'block';
                defaultIcon.style.display = 'none';
            } else {
                albumArt.style.display = 'none';
                defaultIcon.style.display = 'block';
            }
            
            if (song.isLocal) {
                if (song.blobUrl) {
                    audioPlayer.src = song.blobUrl;
                    audioPlayer.load();
                } else if (song.fileData) {
                    loadFileFromStorage(song);
                }
            } else {
                getAudioSource(song).then(audioUrl => {
                    if (audioUrl) {
                        audioPlayer.src = audioUrl;
                        audioPlayer.load();
                        if (isPlaying) {
                            audioPlayer.play().catch(err => {
                                showError('播放失败: ' + (err.message || '未知错误'));
                            });
                        }
                    } else {
                        showError('无法获取音频源，请尝试其他歌曲');
                    }
                }).catch(err => {
                    showError('获取音频源失败: ' + (err.message || '未知错误'));
                });
            }
        }
        
        function loadFileFromStorage(song) {
            if (typeof wusiFile !== 'undefined') {
                wusiFile.read(song.fileData.filename).then(blob => {
                    const blobUrl = URL.createObjectURL(blob);
                    song.blobUrl = blobUrl;
                    audioPlayer.src = blobUrl;
                    audioPlayer.load();
                    saveLocalMusic();
                }).catch(err => {
                    showError('加载本地文件失败');
                    console.error('文件读取错误:', err);
                });
            } else {
                showError('不支持的文件存储功能');
            }
        }
        
        async function getAudioSource(song) {
            // 使用网易云音乐API获取真实音频源
            try {
                // 主API
                let response = await wusiFetch(`https://music.163.com/api/song/media?id=${song.id}`);
                
                if (!response.ok) {
                    // 备用API
                    response = await wusiFetch(`https://music-api.vercel.app/netease/song/url?id=${song.id}`);
                }
                
                if (!response.ok) {
                    throw new Error('API请求失败');
                }
                
                const data = await response.json();
                return data.data?.[0]?.url || null;
            } catch (err) {
                console.error('获取音频源错误:', err);
                return null;
            }
        }
        
        function updateProgress() {
            if (isNaN(audioPlayer.duration) || audioPlayer.duration === 0) return;
            
            const percent = (audioPlayer.currentTime / audioPlayer.duration) * 100;
            document.getElementById('progressBar').style.width = `${percent}%`;
            document.getElementById('currentTime').textContent = formatTime(audioPlayer.currentTime);
            
            if (currentSongIndex >= 0 && currentSongIndex < currentPlaylist.length) {
                const songItem = playlist.children[currentSongIndex];
                if (songItem) {
                    const durationEl = songItem.querySelector('.song-duration');
                    if (durationEl) {
                        durationEl.textContent = formatTime(audioPlayer.duration);
                    }
                }
            }
        }
        
        function seekAudio(e) {
            const progressBar = e.currentTarget;
            const clickPosition = e.clientX - progressBar.getBoundingClientRect().left;
            const progressWidth = progressBar.clientWidth;
            const percent = (clickPosition / progressWidth);
            
            audioPlayer.currentTime = percent * audioPlayer.duration;
        }
        
        function adjustVolume(e) {
            const volumeBar = e.currentTarget;
            const clickPosition = e.clientX - volumeBar.getBoundingClientRect().left;
            const progressWidth = volumeBar.clientWidth;
            const percent = Math.min(1, Math.max(0, clickPosition / progressWidth));
            
            document.getElementById('volumeBar').style.width = `${percent * 100}%`;
            document.getElementById('volumePercent').textContent = `${Math.round(percent * 100)}%`;
            audioPlayer.volume = percent;
        }
        
        function handleFileSelect(e) {
            const files = e.target.files;
            if (files.length === 0) return;
            
            fileInput.value = '';
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (!file.type.startsWith('audio/')) continue;
                
                const url = URL.createObjectURL(file);
                
                const song = {
                    id: `local-${Date.now()}-${i}`,
                    title: file.name.replace(/\.[^/.]+$/, ""),
                    artist: "本地音乐",
                    album: "本地文件",
                    duration: "0:00",
                    url: url,
                    blobUrl: url, // 缓存Blob URL
                    cover: null,
                    isLocal: true
                };
                
                if (typeof wusiFile !== 'undefined') {
                    const filename = `${Date.now()}-${file.name}`;
                    wusiFile.save(filename, file).then(() => {
                        song.fileData = { filename };
                        saveLocalMusic();
                    }).catch(err => {
                        console.error('文件保存失败:', err);
                    });
                }
                
                addToPlaylist(song);
            }
            
            updatePlaylistCount();
        }
        
        function renderPlaylist() {
            playlist.innerHTML = '';
            
            if (currentPlaylist.length === 0) {
                emptyPlaylist.style.display = 'block';
                return;
            }
            
            emptyPlaylist.style.display = 'none';
            
            currentPlaylist.forEach((song, index) => {
                const songItem = document.createElement('div');
                songItem.className = 'song-item';
                if (index === currentSongIndex) {
                    songItem.classList.add('playing');
                }
                
                songItem.innerHTML = `
                    <div class="song-number">${index + 1}</div>
                    <div class="song-details">
                        <div class="song-item-title">${song.title}</div>
                        <div class="song-item-artist">${song.artist}</div>
                    </div>
                    <div class="song-duration">${song.duration}</div>
                `;
                
                songItem.addEventListener('click', () => {
                    currentSongIndex = index;
                    loadSong(currentSongIndex);
                    if (!isPlaying) {
                        togglePlay();
                    }
                });
                
                playlist.appendChild(songItem);
            });
        }
        
        function addToPlaylist(song) {
            currentPlaylist.push(song);
            renderPlaylist();
            saveLocalMusic();
            
            if (currentPlaylist.length === 1) {
                currentSongIndex = 0;
                loadSong(currentSongIndex);
            }
        }
        
        function updatePlaylistCount() {
            document.querySelectorAll('.playlist-item').forEach(item => {
                const count = currentPlaylist.length;
                item.querySelector('.song-count').textContent = `${count}首`;
            });
        }
        
        async function searchMusic() {
            const query = searchInput.value.trim();
            if (!query) return;
            
            resultsContainer.innerHTML = '<div class="loader"><i class="fas fa-spinner"></i> 搜索中...</div>';
            searchResults.style.display = 'block';
            
            try {
                // 使用网易云音乐API搜索,我没有有效API，故作废
                const response = await wusiFetch(`https://music.163.com/api/search/get/web?s=${encodeURIComponent(query)}&type=1&limit=20`);
                
                if (!response.ok) {
                    throw new Error('搜索失败');
                }
                
                const data = await response.json();
                searchResultsData = data.result.songs || [];
                
                renderSearchResults();
            } catch (err) {
                console.error('搜索错误:', err);
                resultsContainer.innerHTML = '<div class="error-message">搜索失败，请稍后重试</div>';
            }
        }
        
        function renderSearchResults() {
            if (searchResultsData.length === 0) {
                resultsContainer.innerHTML = '<div class="empty-state"><i class="fas fa-search"></i><p>没有找到匹配的歌曲</p></div>';
                return;
            }
            
            resultsContainer.innerHTML = '';
            document.getElementById('resultsCount').textContent = `${searchResultsData.length} 首歌曲`;
            
            searchResultsData.forEach(song => {
                const resultItem = document.createElement('div');
                resultItem.className = 'result-item';
                
                resultItem.innerHTML = `
                    <div class="result-art">
                        <img src="${song.album.picUrl || ''}" onerror="this.style.display='none';this.parentNode.querySelector('i').style.display='block'">
                        <i class="fas fa-music" style="display: none;"></i>
                    </div>
                    <div class="result-details">
                        <div class="result-title">${song.name}</div>
                        <div class="result-artist">${song.artists.map(a => a.name).join(' / ')} - ${song.album.name}</div>
                    </div>
                `;
                
                resultItem.addEventListener('click', () => {
                    const newSong = {
                        id: song.id,
                        title: song.name,
                        artist: song.artists.map(a => a.name).join(' / '),
                        album: song.album.name,
                        duration: formatTime(song.duration / 1000),
                        cover: song.album.picUrl,
                        isLocal: false
                    };
                    
                    addToPlaylist(newSong);
                });
                
                resultsContainer.appendChild(resultItem);
            });
        }
        
        function formatTime(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return `${mins}:${secs < 10 ? '0' : ''}${secs}`;
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', initPlayer);
    </script>
</body>
</html>